Skip to content

BridgeJS: Support generic functions on imported JS APIs - #799

Open
krodak wants to merge 6 commits into
swiftwasm:mainfrom
PassiveLogic:kr/stack-abi-generics-import
Open

BridgeJS: Support generic functions on imported JS APIs#799
krodak wants to merge 6 commits into
swiftwasm:mainfrom
PassiveLogic:kr/stack-abi-generics-import

Conversation

@krodak

@krodak krodak commented Aug 10, 2026

Copy link
Copy Markdown
Member

Summary

Import half of generic function support (#398), split out of #787 per review. An imported @JSFunction can take a type parameter, so one declaration covers every bridged type:

@JSFunction func parse<T: BridgedSwiftGenericBridgeable>(_ json: String) throws(JSException) -> T

let user: User = try parse(jsonString)   // T inferred from the call site

T can be any primitive, String, JSValue, or a @JS struct/enum/final class, bare or as T?, [T], [String: T]. Also works on @JSClass inits, methods and statics, and for return-only generics. Exported generics are rejected with a diagnostic and land separately on top of this ABI.

How it works

  • Values cross on the existing stack ABI. The only new thing on the wire is an i32 type ID per type parameter, so type-agnostic JS glue can pick the right lift/lower.
  • Type IDs are pointer-based, not name-based (per BridgeJS: Support generic functions at the Swift and JavaScript boundary #787 review): each type gets a BridgeJSTypeHandle, its address is the ID. Same-named types in different modules can't collide, and no existentials means it works under Embedded.
  • Each module exports bjs_<Module>_register_type_handles, which hands its IDs to JS; JS pairs them with its codec table by index. Runs eagerly via a new afterInitialize instantiator hook, or lazily on first generic call (worker threads).
  • Conformances are emitted for every @JS type, not just in modules that declare generics, module B can pass module A's type to a generic function (per BridgeJS: Support generic functions at the Swift and JavaScript boundary #787 review).
  • JS containers get one shared codec each (__bjs_arrayCodec etc.); the non-generic array/dict/optional paths now reuse them instead of inlining a copy per thunk (per BridgeJS: Support generic functions at the Swift and JavaScript boundary #787 review on the stack ABI clones).

Builds without generics don't get the JS generic runtime, just a no-op registration hook per module with @JS types.

Test plan

  • Codegen + link snapshots: free functions, inits, methods, statics, mixed/multiple params, return-only, wrapped forms
  • Diagnostics: import constraints, export rejection
  • ImportGenericAPITests: runtime round-trip of every bridgeable type through real JS, including JSON.parse
  • Examples/Embedded builds a generic round-trip in CI
  • Cross-module registration + runtime gating link tests

@krodak krodak self-assigned this Aug 10, 2026
@krodak
krodak requested a review from kateinoigakukun August 10, 2026 14:13
Comment on lines +418 to +432
Bool.bridgeJSTypeID,
Int.bridgeJSTypeID,
Int8.bridgeJSTypeID,
UInt8.bridgeJSTypeID,
Int16.bridgeJSTypeID,
UInt16.bridgeJSTypeID,
Int32.bridgeJSTypeID,
UInt32.bridgeJSTypeID,
UInt.bridgeJSTypeID,
Int64.bridgeJSTypeID,
UInt64.bridgeJSTypeID,
Float.bridgeJSTypeID,
Double.bridgeJSTypeID,
String.bridgeJSTypeID,
JSValue.bridgeJSTypeID,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we put those core type table entries in JavaScriptKit instead of defining in every module?

prefix: "const \(codecVar) = ",
suffix: ";"
)
return codecVar

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we define a codec helper instead of inlining them? I think we can define StackABI codec helpers for any type that can appear in those combinators' element positions. And it should be shared with the one in type table entries.

return jsValue;
}

const __bjs_createGenericPointHelpers = () => ({

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to include the module name to allow name collisions across modules.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh sorry, I reverted that change, will bring it back in a few 🙏🏻

krodak added 6 commits August 12, 2026 00:31
Every module's generated registration function listed the 15 core type
handles before its own types, and every module's JS registration hook
repeated the 15 primitive codec entries. The core types are owned by the
library, not by any module, so define their registration once.

`_bjs_core_register_type_handles` in JavaScriptKit exposes the core handle
buffer under `bjs_core_register_type_handles`; because JavaScriptKit is
linked into every BridgeJS binary, exactly one definition exists in the
final wasm. The link step emits the matching `bjs[...]` hook once per
linked bundle instead of once per module, and drives it before the
per-module hooks. Generated per-module registration now carries only that
module's own `@JS` types, so a module that merely uses generics emits no
registration function at all.

The ordering contract is still enforced on both sides: each hook checks the
codec array length against the count Swift pushed, and a new build-time test
checks the library's core list against
`BridgeType.genericBridgeablePrimitives`, which the link step uses to build
the core codec array.
Two sites described the same stack ABI twice. Container element positions
without a named codec emitted a local `const elemCodec = {lower, lift}`
literal, re-declared at every lower/lift site, and the generic type-handle
registration emitted an anonymous `{lower, lift}` literal per module type.

Emit one named `{lower, lift}` helper per type shape at module scope instead,
next to the combinators and the primitive codec table, and have both the
element positions and the registration table reference it. Helpers for `@JS`
structs and associated-value enums delegate to the existing
`structHelpers`/`enumHelpers` entries rather than re-emitting their
marshalling; the thin adapter is what lets a helper be a module-scope const
even though those tables are populated later, in `createExports`. The
associated-value enum combinator is gone: its adapter is now the type's
helper.

Composed codecs (`[T]`, `T?`, `[String: T]` and their nestings) are hoisted
the same way and deduplicated across the whole glue, so a generated thunk no
longer builds a codec on every call — previously each call ran e.g.
`__bjs_dictCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lower(...)`.

Helper names derived from type names are qualified with the declaring module,
and composed names inherit that qualification from their element, so two
modules declaring same-named `@JS` types cannot mint the same identifier.
Statically known compositions are now hoisted into module-scope consts, so
the combinators run once for them. A generic call site cannot be hoisted: it
resolves its element codec from a runtime type ID, so `[T]`, `T?` and
`[String: T]` parameters rebuilt a codec object on every call.

Cache each combinator's result by element codec object. The element codecs
are themselves module-scope singletons, so the cache is bounded by the number
of distinct type shapes; a WeakMap keeps it from pinning codecs resolved for
types that are never used again. The `JSUndefinedOr` flavour of the optional
combinator differs in behaviour, not just in its element, so it gets its own
cache.
…ames

The link step minted the struct/enum helper factories, the `const`s holding
them, and the keys of the shared `structHelpers` / `enumHelpers` tables from
the type name alone, so two modules declaring a same-named `@JS` type emitted
duplicate top-level `const`s in one glue scope (a load-time SyntaxError).

Qualify all of them with the declaring module, reusing the
`__bjs_codec_<Module>_<Type>` naming already used for the codec helpers:

    __bjs_createStructHelpers_<Module>_<AbiName>
    __bjs_createEnumHelpers_<Module>_<Name>
    __bjs_helpers_<Module>_<Name>
    structHelpers.<Module>_<AbiName> / enumHelpers.<Module>_<Name>

Declaration sites take the module from the skeleton being emitted; reference
sites, which only see a `BridgeType` (a bare type name), resolve it through
the existing `typeOwnerModules` map.

That map cannot disambiguate a name declared by two modules, and three things
downstream stay minted from the bare name regardless: the top-level
`const <Enum>Values` object, the `class <Name>` declaration, and the
`bjs["swift_js_struct_*_<AbiName>"]` wasm import names, which the Swift side
derives from the same name. Reject those inputs at link time with a message
naming both modules and the type, instead of emitting glue that throws at load
time or binds one module's values to the other module's helpers.
@krodak
krodak force-pushed the kr/stack-abi-generics-import branch from 3561938 to 3eeee89 Compare August 11, 2026 22:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants